package cc.booku.owlbox.BottomFragment;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.appcompat.widget.Toolbar;

import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.sunfusheng.marqueeview.MarqueeView;
import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.listener.OnBindViewListener;
import com.timmy.tdialog.listener.OnViewClickListener;

import java.util.ArrayList;
import java.util.List;

import cc.booku.owlbox.AliPay.PayActivity;
import cc.booku.owlbox.DataAcquisition.AcquisitionActivity;
import cc.booku.owlbox.FileOperations.FileoOperations;
import cc.booku.owlbox.R;
import cc.booku.owlbox.RsaUtil.RsaActivity;
import cc.booku.owlbox.Statistics.ChartActivity;
import cc.booku.owlbox.ThanksDonating.TDChartActivity;
import cc.booku.owlbox.ThanksDonating.ThanksDonatingActivity;
import cc.booku.owlbox.UserSettingsPage.CodeCreator;
import cc.booku.owlbox.UserSettingsPage.DataClearActivity;
import cc.booku.owlbox.UserSettingsPage.UserDataActivity;
import cc.booku.owlbox.loadSqlite.DatabaseHelper;


public class fragment_user extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;


    private Toolbar Toolbar;
    private TextView tv_acquisition, tv_thanksmy, tv_download, tv_thanksD, Tv_aboutapp, tv_ip, tv_history, tv_favorites, tv_morefunctions;
    private MarqueeView tv_board;
    private DatabaseHelper helper;
    private SQLiteDatabase db;

    public fragment_user() {
    }

    public static fragment_user newInstance(String param1, String param2) {
        fragment_user fragment = new fragment_user();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_fragment_user, container, false);
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {

        initsqlite();
        LoadToolbar();
        //控件触发
        ControlsTrigger();


        super.onActivityCreated(savedInstanceState);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
    }


    public void initsqlite() {

        helper = new DatabaseHelper(getContext(), "dbdate", null, R.string.db_version);//dbName数据库名
        db = helper.getWritableDatabase();//获取到了 SQLiteDatabase 对象
    }

    private void LoadToolbar() {
        //新页面接收数据


        Toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);

        Toolbar.setTitle("个人中心");
        Toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到用户设置页面
                Intent intent = new Intent(getActivity(), DataClearActivity.class);
                startActivity(intent);
            }
        });

        Toolbar.inflateMenu(R.menu.menu_user);
        //添加menu 菜单点击事件
        Toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_pie_chart:
                        Intent intent = new Intent(getContext(), ChartActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.action_share:
                        Intent textIntent = new Intent(Intent.ACTION_SEND);
                        textIntent.setType("text/plain");
                        textIntent.putExtra(Intent.EXTRA_TEXT, "软件下载地址：" + "https://lanzous.com/b00nltw9a");
                        startActivity(Intent.createChooser(textIntent, "绿色分享，不含推广内容"));
                        break;
                }
                return true;
            }
        });

    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_user, menu);
    }

    private void ControlsTrigger() {
//tv_favorites tv_acquisition tv_ip tv_history tv_aboutapp tv_thanksD tv_thanksmy
        tv_acquisition = (TextView) getActivity().findViewById(R.id.tv_acquisition);
        tv_thanksmy = (TextView) getActivity().findViewById(R.id.tv_thanksmy);
        tv_download = (TextView) getActivity().findViewById(R.id.tv_download);
        tv_thanksD = (TextView) getActivity().findViewById(R.id.tv_thanksD);
        Tv_aboutapp = (TextView) getActivity().findViewById(R.id.tv_aboutapp);
        tv_ip = (TextView) getActivity().findViewById(R.id.tv_ip);
        tv_history = (TextView) getActivity().findViewById(R.id.tv_history);
        tv_favorites = (TextView) getActivity().findViewById(R.id.tv_favorites);
        tv_morefunctions = (TextView) getActivity().findViewById(R.id.tv_morefunctions);
        //滚动动画
        tv_board = (MarqueeView) getActivity().findViewById(R.id.tv_board);
        String BillBoard_V = FileoOperations.readAssetsTxt(getContext(), "TxtData/BillBoard");
        JSONObject objsd = JSONObject.parseObject(BillBoard_V);
        String result1 = objsd.getString("Buser1");
        String result2 = objsd.getString("Buser2");
        String result3 = objsd.getString("Buser3");
        String result4 = objsd.getString("Buser4");
        List<String> messages = new ArrayList<>();
        messages.add(result1);
        messages.add(result2);
        messages.add(result3);
        messages.add(result4);
        tv_board.startWithList(messages, R.anim.anim_bottom_in, R.anim.anim_top_out);

        tv_download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Cursor c = db.rawQuery("select * from downTable", null);
                if (c.getCount() > 0) {
                    Intent intent = new Intent(getActivity(), UserDataActivity.class);
                    //用Bundle携带数据
                    Bundle bundle = new Bundle();
                    //传递name参数为tinyphp
                    bundle.putString("sqlSentence", "downTable");
                    bundle.putString("sqlTitle", "下载管理");
                    intent.putExtras(bundle);
                    startActivity(intent);
                } else {
                    Toast.makeText(getActivity(), "您还没有下载视频", Toast.LENGTH_SHORT).show();
                }
            }
        });


        tv_history.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Toast.makeText(MyselfActivity.this, "历史记录", Toast.LENGTH_SHORT).show();


                //Toast.makeText(getContext(),"历史记录",Toast.LENGTH_SHORT).show();
                Cursor c = db.rawQuery("select * from collectTable", null);
                if (c.getCount() > 0) {
                    Intent intent = new Intent(getContext(), UserDataActivity.class);
                    //用Bundle携带数据
                    Bundle bundle = new Bundle();
                    //传递name参数为tinyphp
                    bundle.putString("sqlSentence", "collectTable");
                    bundle.putString("sqlTitle", "历史纪录");
                    intent.putExtras(bundle);
                    startActivity(intent);
                } else {
                    Toast.makeText(getContext(), "您还没有观看记录", Toast.LENGTH_SHORT).show();

                }

            }
        });


        tv_favorites.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Toast.makeText(getContext(),"我的收藏",Toast.LENGTH_SHORT).show();

                Cursor c = db.rawQuery("select * from loveTable", null);
                if (c.getCount() > 0) {
                    Intent intent = new Intent(getContext(), UserDataActivity.class);
                    //用Bundle携带数据
                    Bundle bundle = new Bundle();
                    //传递name参数为tinyphp
                    bundle.putString("sqlSentence", "loveTable");
                    bundle.putString("sqlTitle", "我的收藏");
                    intent.putExtras(bundle);
                    startActivity(intent);
                } else {
                    Toast.makeText(getActivity(), "您还没有收藏", Toast.LENGTH_SHORT).show();

                }
            }
        });
        tv_morefunctions.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });


        tv_acquisition.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getContext(), AcquisitionActivity.class);
                startActivity(intent);
            }
        });
        tv_thanksmy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //弹窗二维码
                // QrcodeBannerDialog("https://qr.alipay.com/fkx00671y2pxjvug8rdup1b");

                Intent intent = new Intent();
                intent.setClass(getContext(), PayActivity.class);
                startActivity(intent);

            }
        });
        tv_thanksD.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击显示弹窗用于修改

                // Dialogaboutsoft("当前软件版本：" + packageName(UserActivity.this));
                // 关于鸣谢
                Intent intent = new Intent(getContext(), TDChartActivity.class);
                startActivity(intent);


            }
        });


        Tv_aboutapp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击显示弹窗用于修改

                Dialogaboutsoft("当前软件版本：" + packageName(getContext()));


            }
        });


        //信息加密

        tv_ip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(getContext(), RsaActivity.class);
                startActivity(intent);

            }
        });

    }


    public static String packageName(Context context) {
        PackageManager manager = context.getPackageManager();
        String name = null;
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            name = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return name;
    }

    private void Dialogaboutsoft(final String version) {


        new TDialog.Builder(getFragmentManager())
                .setLayoutRes(R.layout.tdialog_about_soft)
                .setScreenWidthAspect(getContext(), 1f)
                .setCancelableOutside(false)
                .setOnBindViewListener(new OnBindViewListener() {   //通过BindViewHolder拿到控件对象,进行修改
                    @Override
                    public void bindView(BindViewHolder bindViewHolder) {
                        bindViewHolder.setText(R.id.tv_version, version);
                    }
                })
                .addOnClickListener(R.id.iv_close)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                        tDialog.dismiss();
                    }
                })
                .create()
                .show();
    }

    private void QrcodeBannerDialog(final String qrurl) {
        new TDialog.Builder(getFragmentManager())
                .setLayoutRes(R.layout.tdialog_qrcode_ad)
                .setScreenHeightAspect(getContext(), 1.0f)
                .setScreenWidthAspect(getContext(), 1.0f)
                .setOnBindViewListener(new OnBindViewListener() {
                    @Override
                    public void bindView(BindViewHolder viewHolder) {
                        //ImageView iv_icon = (ImageView)getActivity().findViewById(R.id.iv_icon);

                        Bitmap bitmap = null;
                        //可对图片进行修改
                        Bitmap logo = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
                        bitmap = CodeCreator.createQRCode(qrurl, 400, 400, logo);
                        if (bitmap != null) {
                            viewHolder.setImageBitmap(R.id.iv_icon, bitmap);
                            viewHolder.setText(R.id.ic_text, "捐赠时请备注昵称及用途");
                        }
                    }
                })
                .addOnClickListener(R.id.iv_close)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                        tDialog.dismiss();
                    }
                })
                .create()
                .show();
    }


}
